package pj.pamper.clw.mvp.model;

import android.text.TextUtils;

import com.example.framelib.entity.VersionEntity;
import com.example.framelib.entity.response.BaseResponse;
import com.example.framelib.mvp.frame.MvpModel;
import com.example.framelib.okhttp.OkHttpUtils;
import com.example.framelib.okhttp.builder.PostFormBuilder;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Keroro on 2017/7/18.
 */

public class MainModel extends MvpModel {
   // private static final String POST_URL = BuildConfig.SERVER_HOST + "wx/novPatrol/add";

    private static final String POST_URL = "http://221.229.221.39:5008/clw/wx/novPatrol/add";

    public Observable<BaseResponse> add(
            final String reportType ,
            final List<File> images ,
            final String reportDesc,
            final File voice ,
            final String tel) {

        return
                Observable.create(new Observable.OnSubscribe<BaseResponse>() {
                    @Override
                    public void call(Subscriber<? super BaseResponse> subscriber) {
                        PostFormBuilder formBuilder = OkHttpUtils.post().url(POST_URL);
                        if (!TextUtils.isEmpty(reportType)) {
                            formBuilder.addParams("reportType", reportType);
                        }

                        if(images!= null && images.size() > 0){
                            formBuilder.addFiles("images", images);
                        }

                        if (!TextUtils.isEmpty(reportDesc)) {
                            formBuilder.addParams("reportDesc", reportDesc);
                        }

                        if(voice!=null){
                            formBuilder.addFile("voice" , "video" + System.currentTimeMillis() , voice);
                        }

                        if(!TextUtils.isEmpty(tel)){
                            formBuilder.addParams("tel", tel);
                        }

                        try {
                            Response response = formBuilder.build().execute();
                            String str = response.body().string();
                            BaseResponse postResponse = new Gson().fromJson(str, BaseResponse.class);
                            subscriber.onNext(postResponse);
                            subscriber.onCompleted();
                        } catch (IOException e) {
                            e.printStackTrace();
                            subscriber.onError(e);
                        }
                    }
                });
    }

    public Observable<BaseResponse<VersionEntity>> checkVersion() {
        return mApiService.checkVersion();
    }

}
